<template>
  <div class="pageContent" v-if="1">
    <text>手机号</text>
    <input class="memberItIn" v-model="formData.telephone" />
    <view class="btMain">
      <button class="btOne" @click="getText()">粘贴手机号</button>
      <button class="btOne" @click="returnMain(0)">获取房间号登录</button>
    </view>

    <text>openId</text>
    <input class="memberItIn" v-model="formData.openId" />
    <text>roomIdNow</text>
    <input class="memberItIn" v-model="formData.roomIdNow" />
    <button class="btOne" @click="copyText()">复制当前openId</button>
    <text>当前用户的openId</text>
    <input class="memberItIn" v-model="openId" />
    <image class="userIcon" :src="userInfo.avatarUrl"></image>
    <button open-type="getUserInfo" @getuserinfo="bindGetUserInfo">授权登录</button>
    <button @click="getUserProfile"> 获取头像昵称 </button>
  </div>
</template>

<script>
  import {
    mapState
  } from 'vuex'
  import util from '../../../../static/utils/util.js'
  import config from '../../../../static/config.js'
  var socketOpen = false;
  export default {
    data() {
      return {
        images: config.images,
        localImages: config.localImages,
        openId: "",
        formData: {
          "telephone": "18874183954",
          "roomIdNow": "22918",
          "openId": "onZpA5JuIaDlrDdaANOGGUcdo-g0",
          "roomId": "",
        },
        userInfo: "",
      }
    },
    computed: {
      ...mapState({
        myInfo: state => state.user.myInfo
      })
    },
    onLoad() {
      var formData = {
        "telephone": "18874183954",
        "roomIdNow": "22918",
        "openId": "onZpA5JuIaDlrDdaANOGGUcdo-g0"
      }
      this.formData = formData
      this.formData['roomId'] = this.formData.roomIdNow
      var openId = wx.getStorageSync('openId');
      this.openId = openId;

      this.findPermit();
      this.socketTest();
    },
    onShow() {},
    methods: {
      getUserProfile(e) {
        var userInfo = wx.getStorageSync('userInfo')
        if (!userInfo) {
          wx.getUserProfile({
            desc: '用于展示用户头像信息',
            success: (res) => {
              var userInfo = res.userInfo;
              wx.setStorageSync('userInfo', userInfo)
              this.userInfo = userInfo;
            },
            complete(res) {
              console.warn('getUserProfile', res);
            },
          })
        }
      },
      bindGetUserInfo(e) {
        console.warn(e)
      },
      findPermit() {
        // 查看是否授权
        wx.getSetting({
          success(res) {
            if (res.authSetting['scope.userInfo']) {
              // 已经授权，可以直接调用 getUserInfo 获取头像昵称
              wx.getUserInfo({
                success: function(res) {
                  console.warn(res.userInfo)
                }
              })
            }
          }
        })
      },
      returnMain(type = 0) {
        var phoneNumber = this.formData.telephone;
        wx.setStorageSync('phone', phoneNumber);
        wx.setStorageSync('openId', this.formData.openId);
        // var phoneNumber=15974116634;//测试登录手机号
        if (type == 0) {
          this.ownerRoomList(phoneNumber);
        }
        if (type == 1) {
          this.noticeList(this.formData);
        }
      },

      //获取业主该手机号绑定的房屋列表-测试接口
      ownerRoomList(phoneNumber) {
        var params = {
          telephone: phoneNumber,
          agen: 132,
        }
        util.wxRequestPro('/UserServer/room/ownerRoomList', params)
          .then((res) => {
            console.warn('ownerRoomList', res)
            var param = res.param;
            //未录入用户
            if (!param) {
              //清空room列表
              this.$store.commit('updateRoomlist', [])
              wx.redirectTo({
                url: '/pages/subMe/houseList/main'
              })
            }
            //用户有多个房屋
            else if (param.length > 1) {
              //缓存room列表
              this.$store.commit('updateRoomlist', param)
              wx.redirectTo({
                url: '/pages/subMe/houseList/main'
              })
            } else if (param.length == 1) {
              var room = param[0];
              this.noticeList(room)
            }
          }).catch((res) => {
            console.warn('ownerRoomList', res)
            if (res.statusCode == 400) {
              wx.showToast({
                title: '手机没有绑定房屋',
                icon: 'none'
              })
            }
          })
      },

      noticeList(room) {
        return new Promise((resolve, reject) => {
          var url = '/UserServer/weChat/ownerLogin'
          var phone = wx.getStorageSync('phone');
          var openId = wx.getStorageSync('openId');
          var userInfo = wx.getStorageSync('userInfo');
          var params = {
            "telephone": phone,
            "roomIdNow": room.roomId,
            "openId": openId,
            "portraitUrl": userInfo.avatarUrl
          }
          // var params={"telephone":"18373086780","roomIdNow":"6","openId":"otS_J5BacQniO0hwPeE_o0yC42Wo"}
          // var params={"telephone":"15974116634","roomIdNow":"3","openId":"otS_J5E6cSst7DewGBNO1RQwLZLw"}
          util.wxRequestPro(url, params, "POST").then((res) => {
            console.warn('ownerLogin', res)
            var param = res.param
            wx.setStorageSync('room', room);
            wx.setStorageSync('userMsg', param);
            //获取tim用户信息，登录TIM视频通话
            this.handleLogin();
            // wx.switchTab({ url: '/pages/index/main' })
          }).catch((res) => {
            console.warn('catch=ownerLogin', res)
          })
        })
      },

      // 点击登录进行初始化
      handleLogin() {
        var userMsg = wx.getStorageSync('userMsg');
        if (userMsg) {
          var userID = userMsg.im_userId
          // case1: 要登录的用户是当前已登录的用户，则直接跳转即可
          console.warn('this.myInfo', this.myInfo, this.myInfo.userID, userID)
          if (this.myInfo.userID && userID === this.myInfo.userID) {
            wx.switchTab({
              url: '/pages/index/main'
            })
            return
          }
          // case3: 正常登录流程
          this.login(userMsg)
        } else {
          wx.switchTab({
            url: '/pages/index/main'
          })
        }
      },
      login(userMsg) {
        // var userID = 'user2'
        // let userSig = genTestUserSig(userID).userSig
        var userID = userMsg.im_userId
        var userSig = userMsg.userSig
        wx.$app.login({
          userID: userID,
          userSig: userSig
        }).then((res) => {
          console.warn('login=', res)
          this.$store.commit('setRtcConfig', {
            userID: userID,
            userSig: userSig,
            sdkAppID: wx.$sdkAppID
          })
          wx.switchTab({
            url: '/pages/index/main'
          })
        }).catch(() => {
          wx.switchTab({
            url: '/pages/index/main'
          })
        })
      },
      copyText() {
        wx.setClipboardData({
          data: this.openId,
          success(res) {
            wx.getClipboardData({
              success(res) {
                console.warn(res.data) // data
              }
            })
          }
        })
      },
      getText() {
        var self = this;
        wx.getClipboardData({
          success(res) {
            console.warn(res.data) // data
            self.formData.telephone = res.data;
          }
        })
      },

      socketTest() {
        var token = wx.getStorageSync('token');
        //本地服务器地址
        var wsApi = "ws://192.168.0.229:8761/smartWebsocket/" + token;
        //建立连接
        wx.connectSocket({
          url: wsApi,
          header: {
            'content-type': 'application/json'
          },
          success: function() {
            console.warn("客户端连接成功！");
            wx.onSocketOpen(function() {
              console.log('webSocket已打开！');
              var json = {
                "event": "pong"
              }
              json = JSON.stringify(json)
              wx.onSocketMessage(function(msg) {
                console.warn('webSocket', msg);
                var message = JSON.parse(msg.data);
                if (message.event == 'ping') {
                  //向服务器发送消息
                  wx.sendSocketMessage({
                    data: json
                  })
                }
              })
              wx.sendSocketMessage({
                data: json
              })
            })
          }
        })
      },

    }
  }
</script>

<style lang="stylus" scoped>
  .pageContent {}

  .memberItIn {
    width: 700rpx;
    border: 1rpx solid;
  }

  .loginIm {
    width: 630rpx;
    height: 456rpx;
    margin: 100rpx 0rpx 150rpx 60rpx;
  }

  .loginTap {
    display: flex;
    justify-content: center;
  }

  .loginIc {
    width: 50rpx;
    height: 50rpx;
    margin-right: 20rpx;
  }

  .loginTil {
    font-size: 36rpx;
    font-weight: bold;
  }

  .loginTeIm {
    position: absolute;
    width: 370rpx;
    height: 50rpx;
    left: 50%;
    margin-left: -185rpx;
    margin-top: 20rpx;
  }

  .handler {
    margin-top: 200rpx;
    display: flex;
    justify-content: space-between;
    padding: 0 60rpx;
    box-sizing: border-box;
    width: 100%;
  }

  .btMain {
    display: flex;
    flex-direction: row;
  }

  .btOne {
    width: 300rpx;
  }

  .btOne.btDefalt {
    opacity: 0.6;
  }

  .userIcon {
    width: 48rpx;
    height: 48rpx;
    background: #666;
  }
</style>
